package cn.t215.cloud.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

@Slf4j
public class IpFilter extends ZuulFilter {
    private List<String> blackIpList = Arrays.asList("127.0.0.1");
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String addr = ctx.getRequest().getRemoteAddr();
        if(log.isDebugEnabled()) {
            log.debug("addr:{}", addr);
        }
        if(blackIpList.contains(addr)) {
            ctx.setSendZuulResponse(false);//不需要将当前请求转发给后端的微服务
            ctx.set("sendForwardFilter.ran", true);//不需要将当前请求转发给本地
            ctx.setResponseBody("{\"msg\":\"非法访问\"}");
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            ctx.set("isSuccess", false);//通知后续的过滤器不要执行
            //后续的过滤器中的代码如下
//            boolean success = (boolean) ctx.get("isSuccess");
            //过滤器中shouldFilter方法中判断
//            if(success) {//执行
//
//            }
        }
        return null;
    }
}
